<template>
  <div class="chat-room">
    <!-- 左侧会话列表 -->
    <div class="chat-sidebar">
      <div class="sidebar-header">
        <h3>咨询会话</h3>
        <el-button type="primary" @click="createNewChat">发起咨询</el-button>
      </div>
      
      <!-- 搜索框 -->
      <div class="search-box">
        <el-input
          v-model="searchText"
          placeholder="搜索会话..."
          prefix-icon="Search"
          clearable
        />
      </div>
      
      <!-- 会话列表 -->
      <div class="session-list">
        <div v-if="chatList.length === 0" class="empty-tip">
          暂无会话
        </div>
        <div
          v-else
          v-for="session in chatList"
          :key="session.id"
          class="session-item"
          :class="{ active: currentSession?.id === session.id }"
          @click="handleSelectSession(session)"
        >
          <el-avatar 
            :size="40" 
            :src="currentUserRole === 'student' ? 
              (session.counselorAvatar || defaultAvatar) : 
              (session.studentAvatar || defaultAvatar)" 
          />
          <div class="session-info">
            <div class="name">
              {{ currentUserRole === 'student' ? session.counselorName : session.studentName }}
            </div>
            <div class="last-message">{{ session.lastMessage || '暂无消息' }}</div>
          </div>
          <div v-if="getUnreadCount(session) > 0" class="unread-count">
            {{ getUnreadCount(session) }}
          </div>
        </div>
      </div>
    </div>

    <!-- 右侧聊天区域 -->
    <div class="chat-main">
      <template v-if="currentSession">
        <div class="chat-header">
          <div class="header-left">
            <div class="user-info">
              <div class="status-tag">
                <span class="name">
                  {{ currentUserRole === 'student' ? currentSession?.counselorName : currentSession?.studentName }}
                </span>
                <el-tag 
                  :type="currentSession?.status === 'ACTIVE' ? 'success' : 'warning'" 
                  size="small"
                >
                  {{ currentSession?.status === 'ACTIVE' ? '进行中' : '已结束' }}
                </el-tag>
                <span class="session-time" v-if="currentSession?.startTime">
                  {{ formatSessionTime(currentSession.startTime) }} - {{ formatSessionTime(currentSession.endTime) }}
                </span>
              </div>
            </div>
          </div>
          <div class="header-right">
            <el-button-group>
              <el-button 
                v-if="currentUserRole !== 'student'"  
                :icon="Document" 
                @click="handleEditRecord"
              >
                编辑记录
              </el-button>
              <el-button 
                v-if="currentSession.status === 'ACTIVE'"
                :icon="CircleClose" 
                type="danger" 
                @click="handleEndSession"
              >
                结束会话
              </el-button>
            </el-button-group>
          </div>
        </div>
        
        <div class="chat-content" ref="chatContentRef">
          <div v-if="messages.length === 0" class="empty-tip">
            暂无消息，开始咨询吧
          </div>
          <template v-else>
            <div 
              v-for="(message, index) in messages" 
              :key="index"
              class="message-item"
              :class="{ 
                'message-self': message.isSelf,
                'message-system': message.type === 'system'
              }"
            >
              <!-- 系统消息的特殊显示 -->
              <template v-if="message.type === 'system'">
                <div class="system-message">
                  <el-icon><InfoFilled /></el-icon>
                  <span>{{ message.content }}</span>
                </div>
              </template>
              
              <!-- 普通消息的显示 -->
              <template v-else>
                <div class="message-time" v-if="showMessageTime(message, index)">
                  {{ formatTime(message.time) }}
                </div>
                <div class="message-content">
                  <el-avatar 
                    :size="36"
                    :src="message.isSelf ? 
                      (userAvatar || defaultAvatar) : 
                      (message.senderAvatar || defaultAvatar)"
                  />
                  <div class="message-info">
                    <div class="sender-name">{{ message.isSelf ? '我' : message.senderName }}</div>
                    <div class="message-wrapper">
                      <div class="message-bubble" :class="message.type">
                        <!-- 文本消息 -->
                        <template v-if="message.type === 'text'">
                          <div class="text-message">{{ message.content }}</div>
                        </template>
                        
                        <!-- 图片消息 -->
                        <template v-else-if="message.type === 'image'">
                          <div class="image-message">
                            <el-image 
                              :src="message.fileUrl" 
                              :preview-src-list="[message.fileUrl]"
                              fit="cover"
                            />
                          </div>
                        </template>
                        
                        <!-- 文件消息 -->
                        <template v-else-if="message.type === 'file'">
                          <div class="file-message">
                            <el-link 
                              :href="message.fileUrl" 
                              target="_blank"
                              type="primary"
                            >
                              <el-icon><Document /></el-icon>
                              {{ message.fileName || '文件' }}
                            </el-link>
                          </div>
                        </template>
                      </div>
                      
                      <!-- 消息操作 -->
                      <div class="message-actions" v-if="canRecallMessage(message)">
                        <el-dropdown trigger="hover" @command="handleMessageAction($event, message)">
                          <el-icon><More /></el-icon>
                          <template #dropdown>
                            <el-dropdown-menu>
                              <el-dropdown-item command="recall">撤回</el-dropdown-item>
                            </el-dropdown-menu>
                          </template>
                        </el-dropdown>
                      </div>
                      
                      <!-- 消息状态 -->
                      <div class="message-status" v-if="message.isSelf">
                        <el-icon v-if="message.status === 'SENDING'" class="sending"><Loading /></el-icon>
                        <el-icon v-else-if="message.status === 'DELIVERED'" class="sent"><Select /></el-icon>
                        <el-icon v-else-if="message.status === 'ERROR'" class="error"><Warning /></el-icon>
                      </div>
                    </div>
                  </div>
                </div>
              </template>
            </div>
          </template>
        </div>

        <!-- 聊天输入区域 -->
        <div class="chat-input-area">
          <!-- 如果会话已结束，显示提示 -->
          <template v-if="currentSession?.status === 'CLOSED'">
            <div class="session-ended-notice">
              <el-icon><InfoFilled /></el-icon>
              <span>会话已结束，无法继续发送消息</span>
            </div>
          </template>
          <!-- 如果会话未结束，显示正常的输入区域 -->
          <template v-else>
            <div class="toolbar">
              <div class="tool-items">
                <div class="tool-item">
                  <svg class="icon" viewBox="0 0 1024 1024" width="24" height="24">
                    <path d="M896 626.592V224c0-53.024-42.976-96-96-96H224c-53.024 0-96 42.976-96 96v576c0 53.024 42.976 96 96 96h576c53.024 0 96-42.976 96-96v-2.592l-96-96v98.592H224V224h576v402.592l96-96z" fill="currentColor"/>
                    <path d="M384 384c-35.392 0-64 28.608-64 64s28.608 64 64 64 64-28.608 64-64-28.608-64-64-64z" fill="currentColor"/>
                  </svg>
                </div>
                <div class="tool-item">
                  <svg class="icon" viewBox="0 0 1024 1024" width="24" height="24">
                    <path d="M512 642.048c70.656 0 128-57.344 128-128v-256c0-70.656-57.344-128-128-128s-128 57.344-128 128v256c0 70.656 57.344 128 128 128z m-256-128c0 141.376 114.624 256 256 256s256-114.624 256-256h-64c0 106.048-85.952 192-192 192s-192-85.952-192-192h-64z" fill="currentColor"/>
                    <path d="M480 768h64v128h-64z" fill="currentColor"/>
                  </svg>
                </div>
                <div class="tool-item emoji-trigger" @click.stop="toggleEmojiPicker">
                  <svg class="icon" viewBox="0 0 1024 1024" width="24" height="24">
                    <path d="M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64z m0 832c-212.1 0-384-171.9-384-384s171.9-384 384-384 384 171.9 384 384-171.9 384-384 384z" fill="currentColor"/>
                    <path d="M512 704c93.9 0 173.3-59.7 203.2-143.1 5.8-16.3-2.7-34.2-19-40-16.3-5.8-34.2 2.7-40 19C635.5 594.7 578 640 512 640c-66 0-123.5-45.3-144.2-100.1-5.8-16.3-23.7-24.8-40-19-16.3 5.8-24.8 23.7-19 40C338.7 644.3 418.1 704 512 704z" fill="currentColor"/>
                    <path d="M384 384m-48 0a48 48 0 1 0 96 0 48 48 0 1 0-96 0Z" fill="currentColor"/>
                    <path d="M640 384m-48 0a48 48 0 1 0 96 0 48 48 0 1 0-96 0Z" fill="currentColor"/>
                  </svg>
                </div>
              </div>
            </div>

            <!-- 表情选择器 -->
            <div v-show="showEmojiPicker" class="emoji-picker">
              <div class="emoji-tabs">
                <div 
                  v-for="(tab, index) in emojiTabs" 
                  :key="index"
                  class="tab-item"
                  :class="{ active: currentEmojiTab === index }"
                  @click="currentEmojiTab = index"
                >
                  {{ tab.name }}
                </div>
              </div>
              <div class="emoji-container">
                <div 
                  v-for="emoji in currentEmojis" 
                  :key="emoji"
                  class="emoji-item"
                  @click="insertEmoji(emoji)"
                >
                  {{ emoji }}
                </div>
              </div>
            </div>

            <div class="input-area">
              <el-input
                v-model="messageInput"
                type="textarea"
                :rows="3"
                :autosize="{ minRows: 1, maxRows: 4 }"
                placeholder="输入消息..."
                @keyup.enter="handleSendMessage"
                @keyup.ctrl.enter="messageInput += '\n'"
              />
              <el-button 
                type="primary" 
                :disabled="!messageInput.trim()" 
                @click="handleSendMessage"
              >
                发送
              </el-button>
            </div>
          </template>
        </div>
      </template>
      <div v-else class="empty-state">
        <el-empty description="选择一个会话或发起新的咨询" />
      </div>
    </div>

    <!-- 文件上传隐藏input -->
    <input
      ref="fileInputRef"
      type="file"
      style="display: none"
      @change="onFileSelected"
    />

    <!-- 添加记录编辑弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      title="编辑咨询记录"
      width="700px"
    >
      <el-form
        ref="formRef"
        :model="recordForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="主要问题" prop="mainIssue">
          <el-input 
            v-model="recordForm.mainIssue" 
            type="textarea" 
            :rows="3"
            :maxlength="500"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="问题分析" prop="analysis">
          <el-input 
            v-model="recordForm.analysis" 
            type="textarea" 
            :rows="4"
            :maxlength="1000"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="建议" prop="suggestion">
          <el-input 
            v-model="recordForm.suggestion" 
            type="textarea" 
            :rows="3"
            :maxlength="500"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="后续计划" prop="nextPlan">
          <el-input 
            v-model="recordForm.nextPlan" 
            type="textarea" 
            :rows="3"
            :maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitRecord" :loading="submitLoading">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加情绪监测组件，只对咨询师显示 -->
    <EmotionGauge v-if="currentUserRole === 'counselor' && currentSession" :value="emotionValue" />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick, watch, onUpdated, onBeforeUnmount } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import { useStore } from 'vuex'
import { 
  Document, CircleClose, 
  Loading, Select, Warning, More, InfoFilled
} from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
import type { ChatMessage, ChatSessionDisplay, WebSocketResponse } from '@/types/chat'
import { 
  getChatList, 
  getChatHistory, 
  getChatSession,
  markMessagesAsRead,
  recallMessage,
  endChatSession
} from '@/api/chat'
import { analyzeEmotion, getRealtimeEmotion } from '@/api/emotion'
import { useWebSocket } from '@/hooks/useWebSocket'
import request from '@/utils/request'
import EmotionGauge from './EmotionGauge.vue'


dayjs.extend(relativeTime)

const router = useRouter()
const route = useRoute()
const store = useStore()
const loading = ref(false)
const chatList = ref<ChatSessionDisplay[]>([])
const currentSession = ref<ChatSessionDisplay | null>(null)
const messageInput = ref('')
const searchText = ref('')
const messages = ref<ChatMessage[]>([])
const chatContentRef = ref<HTMLElement>()
const fileInputRef = ref<HTMLInputElement>()
const defaultAvatar = 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'

const { sendMessage: sendWebSocketMessage, connect, connected, addMessageHandler, addConfirmHandler } = useWebSocket()

// 计算当前用户和对方用户的ID
const currentUserId = computed(() => store.state.user.id)
const currentUserRole = computed(() => store.state.user.role)

const otherUserId = computed(() => {
  if (!currentSession.value) return 0
  
  // 如果当前用户是学生，对方是咨询师
  if (currentUserRole.value === 'student') {
    return currentSession.value.counselorId
  }
  // 如果当前用户是咨询师，对方是学生
  else if (currentUserRole.value === 'counselor') {
    return currentSession.value.studentId
  }
  return 0
})

// 修改计算属性
const isCounselor = computed(() => {
  return store.state.user.role === 'counselor'
})

// 从路由或会话列表中获取 appointmentId
const appointmentId = computed(() => {
  // 优先使用路由查询参数
  if (route.query.appointmentId) {
    return Number(route.query.appointmentId)
  }
  // 如果没有查询参数，使用会话列表中的第一个会话
  if (chatList.value && chatList.value.length > 0) {
    return chatList.value[0].appointmentId
  }
  return undefined
})

// 获取聊天列表
const loadChatList = async () => {
  console.log('开始加载聊天列表')
  loading.value = true
  try {
    const { data: response } = await getChatList()
    console.log('后端返回的完整响应:', response)
    if (response && response.length > 0) {
      chatList.value = response.map((session: any) => {
        const isStudent = store.state.user.role === 'student'
        return {
          ...session,
          avatar: session[isStudent ? 'counselorAvatar' : 'studentAvatar'] || defaultAvatar,
          name: isStudent ? session.counselorName : session.studentName,
          lastMessage: session.lastMessage || '暂无消息',
          // 确保保留原始名字
          counselorName: session.counselorName,
          studentName: session.studentName
        }
      })
    } else {
      chatList.value = []
    }
  } catch (error) {
    console.error('获取会话列表失败:', error)
    ElMessage.error('获取会话列表失败')
  } finally {
    loading.value = false
  }
}

// 发起新的咨询
const createNewChat = () => {
  router.push('stuappointment')
}

// 选择会话
const handleSelectSession = async (session: ChatSessionDisplay) => {
  console.log('选择会话，角色:', isCounselor.value ? '咨询师' : '学生', '会话:', session)
  
  try {
    const { data } = await getChatSession(session.appointmentId)
    
    currentSession.value = {
      ...data,
      counselorName: session.counselorName,
      studentName: session.studentName,
      name: isCounselor.value ? session.studentName : session.counselorName,
      avatar: isCounselor.value ? 
        (session.studentAvatar || defaultAvatar) : 
        (session.counselorAvatar || defaultAvatar)
    }
    
    await loadChatHistory(session.appointmentId)
    
    // 标记消息为已读
    if ((isCounselor.value && session.counselorUnread > 0) || 
        (!isCounselor.value && session.studentUnread > 0)) {
      try {
        await markMessagesAsRead(session.appointmentId)
        const sessionIndex = chatList.value.findIndex(s => s.appointmentId === session.appointmentId)
        if (sessionIndex !== -1) {
          if (isCounselor.value) {
            chatList.value[sessionIndex].counselorUnread = 0
          } else {
            chatList.value[sessionIndex].studentUnread = 0
          }
        }
      } catch (error) {
        console.error('标记消息已读失败:', error)
      }
    }
    
    scrollToBottom()
  } catch (error) {
    console.error('获取会话信息失败:', error)
    ElMessage.error('获取会话信息失败')
  }
}

// 格式化时间
const formatTime = (time: string) => {
  const date = dayjs(time)
  if (dayjs().diff(date, 'day') <= 7) {
    return date.fromNow()
  }
  return date.format('YYYY-MM-DD HH:mm')
}

// 是否显示消息时间
const showMessageTime = (message: ChatMessage, index: number) => {
  if (index === 0) return true
  const prevMessage = messages.value[index - 1]
  return dayjs(message.time).diff(dayjs(prevMessage.time), 'minute') > 5
}

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (chatContentRef.value) {
      chatContentRef.value.scrollTop = chatContentRef.value.scrollHeight
    }
  })
}

// 情感监测相关状态和函数，只在咨询师角色时使用
const emotionValue = ref(0)
const emotionUpdateInterval = ref<number | null>(null)

// 修改情感值更新逻辑
const updateEmotionValue = async () => {
  if (!isCounselor.value || !currentSession.value) return
  
  try {
    const response = await getRealtimeEmotion(currentSession.value.studentId)
    
    if (response && response.score !== undefined) {
      // 使用动画过渡到新值
      const oldValue = emotionValue.value
      const newValue = response.score
      
      // 平滑过渡
      const steps = 10
      const stepValue = (newValue - oldValue) / steps
      let currentStep = 0
      
      const animate = () => {
        if (currentStep < steps) {
          emotionValue.value = oldValue + (stepValue * currentStep)
          currentStep++
          requestAnimationFrame(animate)
        } else {
          emotionValue.value = newValue
        }
      }
      
      requestAnimationFrame(animate)
      
      // 高风险提醒
      if (response.riskLevel === 'HIGH_RISK') {
        ElMessage({
          type: 'warning',
          message: '检测到学生情绪风险较高，请及时关注',
          duration: 5000
        })
      }
    }
  } catch (error) {
    console.error('获取情感值失败:', error)
  }
}

// 优化情感监测启动逻辑
const startEmotionMonitoring = () => {
  if (!isCounselor.value) return
  
  // 初始获取
  updateEmotionValue()
  
  // 设置更新间隔
  emotionUpdateInterval.value = window.setInterval(() => {
    updateEmotionValue()
  }, 10000)
}

// 分析消息情感
const analyzeMessageEmotion = async (content: string, tempMessageId: number) => {
  try {
    // 等待WebSocket确认消息返回真实ID
    const realMessageId = await new Promise<number>((resolve, reject) => {
      const timeout = setTimeout(() => {
        reject(new Error('等待消息ID超时'));
      }, 5000);

      // 添加一次性确认消息处理器
      const handler = (confirmedId: number) => {
        if (confirmedId) {
          clearTimeout(timeout);
          resolve(confirmedId);
        }
      };
      
      addConfirmHandler(handler);
    });

    console.log('收到真实消息ID:', realMessageId);

    // 使用真实ID进行情感分析
    const result = await analyzeEmotion(content, store.state.user.id, realMessageId);
    console.log('情感分析结果:', result);

    if (result.riskLevel === 'HIGH_RISK') {
      ElMessage.warning('检测到学生情绪风险较高，请及时关注');
    }

    return result;
  } catch (error) {
    console.error('情感分析失败:', error);
    ElMessage.error('情感分析失败');
    return null;
  }
};

// 停止情感监测
const stopEmotionMonitoring = () => {
  if (emotionUpdateInterval.value) {
    clearInterval(emotionUpdateInterval.value)
    emotionUpdateInterval.value = null
  }
}

// 修改发送消息方法
const handleSendMessage = async () => {
  if (!currentSession.value || !messageInput.value.trim()) {
    return;
  }
  
  const messageContent = messageInput.value.trim();
  console.log('准备发送消息:', messageContent);
  
  // 先清空输入框，提升用户体验
  messageInput.value = '';
  
  // 构造消息对象
  const message = {
    sessionId: currentSession.value?.id,
    content: messageContent,
    type: 'text',
    appointmentId: currentSession.value?.appointmentId,
    receiverId: otherUserId.value
  };
  
  // 声明在外部以便catch块可以访问
  let tempMessage: ChatMessage | null = null;
  
  try {
    // 添加临时消息到UI
    tempMessage = {
      id: Date.now(),
      appointmentId: currentSession.value?.appointmentId || 0,
      content: messageContent,
      type: 'text',
      senderId: store.state.user.id,
      receiverId: otherUserId.value,
      time: new Date().toISOString(),
      status: 'SENDING',
      isSelf: true,
      senderName: store.state.user.name || '我',
      senderAvatar: store.state.user.avatar || defaultAvatar
    };
    messages.value.push(tempMessage);
    scrollToBottom();
    
    console.log('开始发送WebSocket消息:', message);
    await sendWebSocketMessage(message);
    console.log('WebSocket消息发送成功');
    
    // 如果是学生，发送消息后进行情感分析
    if (!isCounselor.value) {
      console.log('是学生角色，开始进行情感分析');
      try {
        // 等待情感分析完成
        const emotionResult = await analyzeMessageEmotion(messageContent, tempMessage.id);
        if (emotionResult && typeof emotionResult.score === 'number') {
          emotionValue.value = emotionResult.score;
          console.log('更新情感值为:', emotionResult.score);
        }
      } catch (error) {
        console.error('情感分析失败:', error);
      }
    }
  } catch (error) {
    console.error('发送消息失败:', error);
    ElMessage.error('发送消息失败');
    // 发送失败时恢复消息内容
    messageInput.value = messageContent;
    // 移除临时消息
    if (tempMessage) {
      messages.value = messages.value.filter(m => m.id !== tempMessage!.id);
    }
  }
};

// 加载历史消息
const loadChatHistory = async (appointmentId: number) => {
  try {
    const { data } = await getChatHistory(appointmentId)
    messages.value = data.map((msg: ChatMessage) => ({
      ...msg,
      isSelf: msg.senderId === store.state.user.id,
      senderName: msg.senderId === store.state.user.id ? '我' : currentSession.value?.name,
      senderAvatar: msg.senderId === store.state.user.id ? 
        (store.state.user.avatar || defaultAvatar) : 
        currentSession.value?.avatar
    }))
    console.log('加载消息历史:', messages.value)
    scrollToBottom()
  } catch (error) {
    console.error('加载消息历史失败:', error)
    ElMessage.error('加载消息历史失败')
  }
}

// 修改 watch appointmentId 的部分
watch(
  appointmentId,
  async (newAppointmentId) => {
    console.log('appointmentId 变化:', newAppointmentId)
    if (newAppointmentId) {
      try {
        // 获取会话信息
        const { data } = await getChatSession(newAppointmentId)
        currentSession.value = {
          ...data,
          name: store.state.user.role === 'student' ? data.counselorName : data.studentName,
          avatar: store.state.user.role === 'student' ? 
            (data.counselorAvatar || defaultAvatar) : 
            (data.studentAvatar || defaultAvatar)
        }
        console.log('获取到会话信息:', currentSession.value)
        
        // 加载历史消息
        await loadChatHistory(newAppointmentId)
      } catch (error) {
        console.error('获取会话信息失败:', error)
        ElMessage.error('获取会话信息失败')
      }
    } else {
      // 如果没有 appointmentId，清空当前会话和消息
      currentSession.value = null
      messages.value = []
    }
  },
  { immediate: false }  // 修改为 false，不要立即执行
)

// 计算当前会话信息
const currentSessionInfo = computed(() => {
  if (!currentSession.value) {
    console.warn('当前会话未初始化')
    return {
      sessionId: undefined,
      appointmentId: undefined,
      currentUserId: store.state.user.id,
      role: store.state.user.role
    }
  }
  
  return {
    sessionId: currentSession.value?.id,
    appointmentId: currentSession.value?.appointmentId,
    currentUserId: store.state.user.id,
    role: store.state.user.role
  }
})

// 结束会话
const handleEndSession = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要结束当前会话吗？结束后将无法继续发送消息。',
      '结束会话',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    if (!currentSession.value?.appointmentId) {
      ElMessage.error('会话信息不完整')
      return
    }
    
    await endChatSession(currentSession.value.appointmentId)
    
    // 更新当前会话状态
    currentSession.value.status = 'CLOSED'
    
    // 更新会话列表中的状态
    const sessionIndex = chatList.value.findIndex(
      s => s.appointmentId === currentSession.value?.appointmentId
    )
    if (sessionIndex !== -1) {
      chatList.value[sessionIndex].status = 'CLOSED'
    }
    
    // 禁用输入框
    messageInput.value = ''
    
    // 不在这里添加系统消息，等待 WebSocket 通知
    ElMessage.success('会话已结束')
    
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '结束会话失败')
    }
  }
}

// 导出聊天记录
const exportChat = () => {
  // TODO: 实现导出功能
  ElMessage.success('聊天记录已导出')
}

// 处理图片上传
const handleImageUpload = () => {
  fileInputRef.value!.accept = 'image/*'
  fileInputRef.value!.click()
}

// 处理文件上传
const handleFileUpload = () => {
  fileInputRef.value!.accept = '*/*'
  fileInputRef.value!.click()
}

// 处理文件选择
const onFileSelected = (event: Event) => {
  const file = (event.target as HTMLInputElement).files?.[0]
  if (file) {
    // TODO: 实现文件上传逻辑
    ElMessage.success('文件上传成功')
  }
  // 重置input
  (event.target as HTMLInputElement).value = ''
}

// 表情相关
const showEmojiPicker = ref(false)
const currentEmojiTab = ref(0)

const emojiTabs = [
  {
    name: '表情',
    emojis: [
      '😀', '😃', '😄', '😁', '😆', '😅', '😂', '🤣', '😊', '😇',
      '😉', '😌', '😍', '🥰', '😘', '😗', '😙', '😚', '😋', '😛',
      '😝', '😜', '🤪', '🤨', '🤓', '😎', '🥳', '😏', '😒', '😞',
      '😔', '😟', '😕', '🙁', '😣', '😖', '😫', '😩', '🥺', '😢',
      '😭', '😤', '😠', '😡', '🤬', '🤯', '😳', '🥵', '🥶', '😱'
    ]
  },
  {
    name: '动物',
    emojis: [
      '🐶', '🐱', '🐭', '🐹', '🐰', '🦊', '🐻', '🐼', '🐨', '🐯',
      '🦁', '🐮', '🐷', '🐸', '🐵', '🐔', '🐧', '🐦', '🐤', '🦆',
      '🦅', '🦉', '🦇', '🐺', '🐗', '🐴', '🦄', '🐝', '🐛', '🦋',
      '🐌', '🐞', '🐜', '🦗', '🕷', '🦂', '🦕', '🦖', '🦎', '🐍',
      '🐢', '🐙', '🦑', '🦐', '🦞', '🦀', '🐡', '🐠', '🐟', '🐬'
    ]
  },
  {
    name: '食物',
    emojis: [
      '🍎', '🍐', '🍊', '🍋', '🍌', '🍉', '🍇', '🍓', '🍈', '🍒',
      '🍑', '🥭', '🍍', '🥥', '🥝', '🍅', '🥑', '🥦', '🥬', '🥒',
      '🌶', '🌽', '🥕', '🥔', '🍠', '🥐', '🥯', '🍞', '🥖', '🥨',
      '🧀', '🥚', '🍳', '🥞', '🧇', '🥓', '🥩', '🍗', '🍖', '🦴',
      '🌭', '🍔', '🍟', '🍕', '🥪', '🥙', '🧆', '🌮', '🌯', '🥗'
    ]
  }
]

const currentEmojis = computed(() => emojiTabs[currentEmojiTab.value].emojis)

// 切换表情选择器
const toggleEmojiPicker = () => {
  showEmojiPicker.value = !showEmojiPicker.value
}

// 插入表情
const insertEmoji = (emoji: string) => {
  messageInput.value += emoji
}

// 语音相关
const startRecording = async () => {
  try {
    const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
    // TODO: 实现录音逻辑
    ElMessage.success('开始录音')
  } catch (error) {
    ElMessage.error('无法访问麦克风')
  }
}

// 播放语音
const playVoice = (message: ChatMessage) => {
  // TODO: 实现语音播放逻辑
  ElMessage.success('播放语音消息')
}

// 添加定时检查消息状态的函数
const checkMessagesStatus = () => {
  if (!messages.value.length) return
  
  const now = dayjs()
  let hasChanges = false
  
  messages.value.forEach(message => {
    // 只检查自己发送的、已送达的消息
    if (message.isSelf && message.status === 'DELIVERED') {
      const messageTime = dayjs(message.time)
      // 如果消息超过2分钟
      if (now.diff(messageTime, 'minute') > 2) {
        message.status = 'EXPIRED'  // 添加一个新的状态表示超时
        hasChanges = true
      }
    }
  })
  
  // 如果有状态变化，强制更新视图
  if (hasChanges) {
    messages.value = [...messages.value]
  }
}

// 修改消息撤回验证函数
const canRecallMessage = (message: ChatMessage) => {
  // 只有自己发送的消息可以撤回
  if (!message.isSelf) {
    return false
  }

  // 消息必须是已送达状态
  if (message.status !== 'DELIVERED') {
    return false
  }

  // 检查消息ID是否有效
  if (!message.id || message.id === Date.now()) {
    return false
  }

  // 计算消息发送时间是否在2分钟内
  const messageTime = dayjs(message.time)
  const now = dayjs()
  const timeDiff = now.diff(messageTime, 'minute')
  const canRecall = timeDiff <= 2

  // console.log('检查消息是否可撤回:', {
  //   messageId: message.id,
  //   isSelf: message.isSelf,
  //   status: message.status,
  //   timeDiff,
  //   canRecall
  // })

  return canRecall
}

// 修改消息操作处理函数
const handleMessageAction = async (action: string, message: ChatMessage) => {
  if (action === 'recall') {
    try {
      // 前端验证
      if (!message.isSelf) {
        throw new Error('只能撤回自己发送的消息')
      }
      
      if (message.status !== 'DELIVERED') {
        throw new Error('消息状态异常，无法撤回')
      }
      
      const messageTime = dayjs(message.time)
      const now = dayjs()
      const timeDiff = now.diff(messageTime, 'minute')
      
      if (timeDiff > 2) {
        throw new Error('消息发送超过2分钟，无法撤回')
      }

      if (!message.id || message.id === Date.now()) {
        throw new Error('无效的消息ID')
      }
      
      try {
        await recallMessage(message.id)
        // 更新本地消息状态
        const index = messages.value.findIndex(m => m.id === message.id)
        if (index !== -1) {
          const updatedMessage = {
            ...messages.value[index],
            content: '此消息已撤回',
            status: 'RECALLED' as const,
            type: 'text' as const
          }
          messages.value.splice(index, 1, updatedMessage)
        }
      } catch (error: any) {
        // 处理后端返回的具体错误信息
        if (error.response?.data?.message) {
          throw new Error(error.response.data.message)
        } else {
          throw new Error('只能撤回2分钟内的消息')
        }
      }
      
      // 更新会话列表中的最后一条消息
      if (message.id === currentSession.value?.lastMessageId) {
        const sessionIndex = chatList.value.findIndex(
          s => s.appointmentId === currentSession.value?.appointmentId
        )
        if (sessionIndex !== -1) {
          const updatedSession = {
            ...chatList.value[sessionIndex],
            lastMessage: '此消息已撤回'
          }
          chatList.value.splice(sessionIndex, 1, updatedSession)
        }
      }
    } catch (error: any) {
      console.error('撤回消息失败:', error)
      // 显示具体的错误信息
      ElMessage({
        message: error.message || '撤回失败',
        type: 'error',
        duration: 3000
      })
    }
  }
}

// 处理接收到的WebSocket消息
const handleWebSocketMessage = (message: WebSocketResponse) => {
  console.log('收到新消息，当前角色:', isCounselor.value, '消息:', message)
  
  // 先判断消息发送者
  const isSelfMessage = message.senderId === store.state.user.id
  
  // 如果是确认消息，更新已发送消息的状态
  if (message.status === 'DELIVERED' && isSelfMessage) {
    const messageIndex = messages.value.findIndex(m => 
      m.status === 'SENDING' && 
      m.content === message.content &&
      m.senderId === message.senderId
    )
    
    if (messageIndex !== -1) {
      const updatedMessage: ChatMessage = {
        ...messages.value[messageIndex],
        id: message.messageId,
        status: 'DELIVERED',
        time: message.time || messages.value[messageIndex].time
      }
      messages.value.splice(messageIndex, 1, updatedMessage)
      return
    }
  }

  // 处理新消息
  if (currentSession.value?.appointmentId === message.appointmentId) {
    // 检查是否已存在相同内容的临时消息
    const existingMessage = messages.value.find(m => 
      m.content === message.content && 
      m.senderId === message.senderId &&
      m.time === message.time
    )
    
    if (existingMessage) {
      console.log('找到已存在的相同消息，跳过添加')
      return
    }
    
    // 创建新消息对象
    const newMessage: ChatMessage = {
      id: message.messageId,
      appointmentId: message.appointmentId,
      content: message.content,
      type: message.type?.toLowerCase() as 'text' | 'image' | 'file',
      senderId: message.senderId,
      receiverId: message.receiverId,
      time: message.time,
      status: 'DELIVERED',
      isSelf: isSelfMessage,
      senderName: isSelfMessage ? '我' : currentSession.value.name,
      senderAvatar: isSelfMessage ? 
        (store.state.user.avatar || defaultAvatar) : 
        currentSession.value.avatar
    }
    
    // 直接添加新消息到列表
    messages.value.push(newMessage)
    scrollToBottom()

    // 如果是咨询师，且收到学生的消息，立即更新情感值
    if (isCounselor.value && !isSelfMessage && message.emotionScore !== undefined) {
      console.log('收到学生消息的情感分析:', message.emotionScore)
      emotionValue.value = message.emotionScore
      
      // 如果有风险等级信息，显示提醒
      if (message.riskLevel === 'HIGH_RISK') {
        ElMessage.warning('检测到学生情绪风险较高，请及时关注')
      }
    }
  }
  
  // 更新会话列表
  updateChatList(message)
}

let reconnectInterval: number | null = null

// 在组件顶部声明定时器变量
const messageStatusTimer = ref<number>()

onMounted(async () => {
  console.log('聊天室组件挂载，当前角色:', isCounselor.value ? '咨询师' : '学生')
  
  if (!store.state.user.id) {
    console.error('用户信息不完整，等待重试')
    return
  }

  try {
    // 先加载会话列表
    await loadChatList()
    
    // 如果有会话列表数据,自动选中第一个会话
    if (chatList.value && chatList.value.length > 0) {
      const urlAppointmentId = route.query.appointmentId
      const targetSession = urlAppointmentId ? 
        chatList.value.find(s => s.appointmentId.toString() === urlAppointmentId) :
        chatList.value[0]
        
      if (targetSession) {
        await handleSelectSession(targetSession)
      }
    }

    // 连接 WebSocket
    await connect()
    
    // 添加消息处理器
    addMessageHandler(handleWebSocketMessage)
    
    // 添加消息确认处理器
    addConfirmHandler(async (messageId) => {
      if (currentSession.value) {
        await loadChatHistory(currentSession.value.appointmentId)
      }
    })

    // 添加定时检查消息状态
    messageStatusTimer.value = window.setInterval(checkMessagesStatus, 30000)

    // 只有咨询师才开启情感监测
    if (isCounselor.value) {
      startEmotionMonitoring()
    }

  } catch (error) {
    console.error('初始化失败:', error)
    ElMessage.error('初始化失败，请刷新页面重试')
  }
})

// 更新会话列表的辅助函数
const updateChatList = (message: WebSocketResponse) => {
  const sessionIndex = chatList.value.findIndex(s => 
    s.appointmentId === message.appointmentId
  )
  
  if (sessionIndex !== -1) {
    const isSelfMessage = message.senderId === store.state.user.id
    
    // 更新最后一条消息
    chatList.value[sessionIndex].lastMessage = message.content
    
    // 更新未读数
    if (!isSelfMessage && currentSession.value?.appointmentId !== message.appointmentId) {
      if (isCounselor.value) {
        chatList.value[sessionIndex].counselorUnread++
      } else {
        chatList.value[sessionIndex].studentUnread++
      }
    }
    
    // 置顶会话
    const updatedSession = chatList.value.splice(sessionIndex, 1)[0]
    chatList.value.unshift(updatedSession)
  }
}

// 监听 chatList 的变化
watch(chatList, (newVal, oldVal) => {
  console.log('chatList 变化')
  console.log('旧值:', oldVal)
  console.log('新值:', newVal)
})

// 监听模板渲染
onUpdated(() => {
  console.log('组件更新')
  console.log('当前 chatList:', chatList.value)
  console.log('session-list 中的元素数量:', document.querySelectorAll('.session-item').length)
})

// 监听用户信息变化
watch(() => store.state.user.id, (newId) => {
  if (newId) {
    console.log('用户ID已更新，重新初始化WebSocket')
    connect()
  }
})

onBeforeUnmount(() => {
  // 清理定时器
  if (reconnectInterval) {
    clearInterval(reconnectInterval)
  }
  if (messageStatusTimer.value) {
    clearInterval(messageStatusTimer.value)
  }
  document.removeEventListener('click', hideEmojiPicker)

  // 只有咨询师才需要停止情感监测
  if (isCounselor.value) {
    stopEmotionMonitoring()
  }
})

// 获取未读消息数
const getUnreadCount = (session: ChatSessionDisplay) => {
  // 根据当前用户角色返回对应的未读数
  if (currentUserRole.value === 'student') {
    return session.studentUnread || 0
  } else {
    return session.counselorUnread || 0
  }
}

// 在 script setup 中添加
const hideEmojiPicker = () => {
  showEmojiPicker.value = false
}

// 获取当前用户头像
const userAvatar = computed(() => store.state.user.avatar || defaultAvatar)

// 修改时间格式化方法
const formatSessionTime = (time: string) => {
  if (!time) return ''
  return dayjs(time).format('YYYY-MM-DD HH:mm:ss')  // 修改为显示完整时间
}

// 添加计算属性来获取显示名字
const displayName = computed(() => {
  if (!currentSession.value) return ''
  return currentUserRole.value === 'student' 
    ? currentSession.value.counselorName 
    : currentSession.value.studentName
})

// 添加计算属性来获取会话时间
const sessionTimeRange = computed(() => {
  if (!currentSession.value?.startTime || !currentSession.value?.endTime) return ''
  return `${formatSessionTime(currentSession.value.startTime)} - ${formatSessionTime(currentSession.value.endTime)}`
})

// 添加对 currentSession 的监听
watch(currentSession, (newSession) => {
  console.log('currentSession changed:', newSession)
  if (newSession) {
    console.log('会话时间:', {
      startTime: newSession.startTime,
      endTime: newSession.endTime,
      formatted: {
        start: formatSessionTime(newSession.startTime),
        end: formatSessionTime(newSession.endTime)
      }
    })
  }
}, { deep: true })

// 添加 WebSocket 连接状态监控
watch(connected, (newVal) => {
  console.log('WebSocket 连接状态:', newVal)
  if (!newVal) {
    ElMessage.warning('聊天服务连接断开，正在重新连接...')
  }
})

// 记录相关
const dialogVisible = ref(false)
const submitLoading = ref(false)

// 修改表单定义，使用接口定义类型
interface RecordForm {
  id: string | number
  mainIssue: string
  analysis: string
  suggestion: string
  nextPlan: string
}

// 使用类型定义初始化表单
const recordForm = ref<RecordForm>({
  id: '',
  mainIssue: '',
  analysis: '',
  suggestion: '',
  nextPlan: ''
})

// 添加表单验证规则
const rules = ref({
  mainIssue: [{ required: true, message: '请输入主要问题', trigger: 'blur' }],
  analysis: [{ required: true, message: '请输入问题分析', trigger: 'blur' }],
  suggestion: [{ required: true, message: '请输入建议', trigger: 'blur' }]
})

// 表单引用
const formRef = ref()

// 修改编辑函数
const handleEditRecord = async () => {
  try {
    console.log('当前会话:', currentSession.value)
    
    const { data } = await request({
      url: `/record/appointment/${currentSession.value?.appointmentId}`,
      method: 'get'
    })
    
    console.log('获取到的记录数据:', data)
    
    // 使用解构赋值确保所有字段都被正确复制
    const { id, mainIssue, analysis, suggestion, nextPlan } = data
    
    // 直接赋值整个对象
    recordForm.value = {
      id,  // 直接使用解构出来的id
      mainIssue: mainIssue || '',
      analysis: analysis || '',
      suggestion: suggestion || '',
      nextPlan: nextPlan || ''
    }
    
    console.log('设置到表单的数据:', recordForm.value)
    dialogVisible.value = true
  } catch (error) {
    console.error('获取记录失败:', error)
    ElMessage.error('获取记录失败')
  }
}

// 提交记录
const submitRecord = async () => {
  submitLoading.value = true
  try {
    console.log('提交前的表单数据:', recordForm.value)
    
    // 使用解构赋值创建提交数据
    const { id, mainIssue, analysis, suggestion, nextPlan } = recordForm.value
    
    const submitData = {
      id,  // 直接使用解构出来的id
      mainIssue,
      analysis,
      suggestion,
      nextPlan
    }
    
    console.log('最终提交的数据:', submitData)
    
    await request({
      url: '/record/update',
      method: 'put',
      data: submitData
    })
    ElMessage.success('保存成功')
    dialogVisible.value = false
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  } finally {
    submitLoading.value = false
  }
}
</script>

<style lang="scss" scoped>
.chat-room {
  display: flex;
  height: calc(100vh - 120px);
  background-color: #fff;
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);

  .chat-sidebar {
    width: 300px;
    border-right: 1px solid #dcdfe6;
    display: flex;
    flex-direction: column;

    .sidebar-header {
      padding: 16px;
      border-bottom: 1px solid #dcdfe6;
      display: flex;
      justify-content: space-between;
      align-items: center;

      h3 {
        margin: 0;
        font-size: 16px;
      }
    }

    .search-box {
      padding: 12px 16px;
      border-bottom: 1px solid #dcdfe6;
    }

    .session-list {
      flex: 1;
      overflow-y: auto;

      .session-item {
        padding: 14px 16px;
        display: flex;
        align-items: flex-start;
        cursor: pointer;
        transition: background-color 0.3s;

        &:hover {
          background-color: #f5f7fa;
        }

        &.active {
          background-color: #ecf5ff;
        }

        .el-avatar {
          margin-right: 12px;
        }

        .session-info {
          flex: 1;
          min-width: 0;

          .name {
            font-size: 14px;
            font-weight: 500;
            color: #303133;
            margin-bottom: 4px;
          }
          
          .last-message {
            font-size: 12px;
            color: #909399;
          }
        }

        .unread-count {
          background-color: #f56c6c;
          color: #fff;
          border-radius: 10px;
          padding: 2px 6px;
          font-size: 12px;
          margin-left: 8px;
        }
      }
    }
  }

  .chat-main {
    flex: 1;
    display: flex;
    flex-direction: column;
    position: relative;

    .chat-header {
      padding: 16px;
      border-bottom: 1px solid #dcdfe6;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .el-tag {
        margin-left: 12px;
      }

      .session-info {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-top: 4px;
        
        .session-time {
          font-size: 12px;
          color: #909399;
        }
      }
    }

    .chat-content {
      flex: 1;
      padding: 20px;
      overflow-y: auto;
      background-color: #f5f7fa;

      .message-item {
        margin-bottom: 20px;

        .message-time {
          text-align: center;
          margin: 16px 0;
          color: #909399;
          font-size: 12px;
        }

        .message-content {
          display: flex;
          align-items: flex-start;
          gap: 12px;
          padding: 0 20px;
        }

        .message-info {
          flex: 1;
          max-width: 70%;

          .sender-name {
            font-size: 13px;
            color: #909399;
            margin-bottom: 6px;
          }

          .message-wrapper {
            position: relative;
            display: flex;
            align-items: flex-end;
          }
        }

        .message-bubble {
          background-color: #fff;
          padding: 10px 14px;
          border-radius: 8px;
          position: relative;
          word-break: break-all;
          box-shadow: 0 2px 4px rgba(0,0,0,0.1);
          font-size: 14px;
          line-height: 1.6;

          &::before {
            content: '';
            position: absolute;
            top: 12px;
            border: 6px solid transparent;
          }

          &.image {
            padding: 4px;
            background-color: transparent;
            box-shadow: none;
          }

          .message-image {
            max-width: 200px;
            max-height: 200px;
            border-radius: 8px;
            cursor: pointer;
          }

          .file-message {
            display: flex;
            align-items: center;
            padding: 8px 12px;
            border-radius: 4px;
            cursor: pointer;
            
            .el-icon {
              margin-right: 4px;
            }
          }
        }

        &.message-self {
          .message-content {
            flex-direction: row-reverse;
          }

          .message-info {
            display: flex;
            flex-direction: column;
            align-items: flex-end;
          }

          .message-bubble {
            background-color: #95ec69;

            &::before {
              right: -12px;
              border-left-color: #95ec69;
            }
          }
        }

        &:not(.message-self) .message-bubble::before {
          left: -12px;
          border-right-color: #fff;
        }

        &.message-system {
          margin: 16px 0;
          display: flex;
          justify-content: center;
          
          .system-message {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 8px 16px;
            background-color: rgba(230, 162, 60, 0.1);
            border-radius: 16px;
            color: #e6a23c;
            font-size: 13px;
            
            .el-icon {
              font-size: 16px;
            }
          }
        }
      }
    }

    .chat-input-area {
      position: relative;
      border-top: 1px solid #dcdfe6;
      background-color: #fff;

      .session-ended-notice {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
        padding: 16px;
        color: #b88230;
        background-color: #fdf6ec;
        font-size: 14px;
        
        .el-icon {
          font-size: 16px;
          color: #e6a23c;
        }
      }

      .toolbar {
        padding: 8px 16px;
        border-bottom: 1px solid #ebeef5;

        .tool-items {
          display: flex;
          gap: 16px;

          .tool-item {
            font-size: 20px;
            color: #8e8e93;
            cursor: pointer;
            padding: 4px;
            border-radius: 4px;
            transition: all 0.3s;
            display: flex;
            align-items: center;
            justify-content: center;

            .icon {
              width: 24px;
              height: 24px;
              fill: currentColor;
            }

            &:hover {
              color: #595959;
            }
          }
        }
      }

      .emoji-picker {
        position: absolute;
        bottom: 100%;
        left: 16px;
        background: #fff;
        border: 1px solid #dcdfe6;
        border-radius: 8px;
        box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
        width: 460px;
        z-index: 1000;

        .emoji-tabs {
          display: flex;
          border-bottom: 1px solid #ebeef5;
          padding: 8px;
          background-color: #f5f7fa;

          .tab-item {
            padding: 4px 12px;
            cursor: pointer;
            border-radius: 4px;
            font-size: 14px;
            color: #606266;
            margin-right: 8px;

            &:hover {
              background-color: #e4e7ed;
            }

            &.active {
              background-color: #ecf5ff;
              color: #409eff;
            }
          }
        }

        .emoji-container {
          display: grid;
          grid-template-columns: repeat(10, 1fr);
          gap: 4px;
          padding: 12px;
          height: auto;

          .emoji-item {
            font-size: 24px;
            cursor: pointer;
            text-align: center;
            padding: 4px;
            border-radius: 4px;
            transition: all 0.2s;
            line-height: 1;
            height: 36px;
            width: 36px;
            display: flex;
            align-items: center;
            justify-content: center;

            &:hover {
              background-color: #f5f7fa;
              transform: scale(1.2);
              z-index: 1;
            }
          }
        }
      }

      .input-area {
        padding: 12px 16px;
        display: flex;
        gap: 12px;
        align-items: flex-end;

        .el-input {
          flex: 1;

          :deep(.el-textarea__inner) {
            resize: none;
            border-radius: 4px;
            padding: 8px 12px;
            min-height: 40px !important;
            max-height: 120px !important;
          }
        }

        .el-button {
          height: 40px;
          padding: 0 20px;
        }
      }
    }

    .empty-state {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }

  .toolbar {
    padding: 8px 16px;
    border-top: 1px solid #dcdfe6;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .typing-status {
      font-size: 12px;
      color: #909399;
    }
  }

  .input-area {
    display: flex;
    gap: 12px;
    padding: 16px;
  }
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.empty-tip {
  text-align: center;
  padding: 20px;
  color: #909399;
}

.chat-header {
  .header-left {
    .user-info {
      .status-tag {
        display: flex;
        align-items: center;
        gap: 12px;
        min-height: 32px;
        padding: 4px 0;

        .name {
          font-size: 14px;
          color: #606266;
          font-weight: 500;
          white-space: nowrap;
        }

        .el-tag {
          margin: 0;
        }

        .session-time {
          font-size: 13px;
          color: #909399;
          white-space: nowrap;
        }
      }
    }
  }
}
</style> 